﻿////////1.0.8
var request = require('request');
const fs = require('fs');
var  singers,datax,buf;



let optionsAr = {
  method:'GET',
  url:'https://api.imjad.cn/cloudmusic', ////id=12057022 黄龙飞
  qs: { type: '', id: '' },
  headers:
  {
    'Cache-Control': 'no-cache' 
  }
};

////输出的数据
let json = {
 updata:()=>{
     return new Promise((reslove, reject)=>{

        datax = fs.readFileSync('./Data/database.json');
        buf = new Buffer.from(datax);
        datax= JSON.parse(buf);
        singers = datax.singer;
        console.log(123)
        reslove();
        
    })
 }
    ,

/////这是一个发送请求的方法，返回值为每一个歌手的信息,其中的hotSongs[index].id为前五十个热门歌曲的id
 request:()=>{
     return  new Promise((reslove, reject)=>{
        optionsAr.qs.type = 'artist';
        let datap = [];
        singers.forEach(function(index,item){
         //请求歌手的song信息;
         optionsAr.qs.id = index.id;
          request(optionsAr,function(err,res,body){
           if(err){
           throw new Error(err);
           }
           else{
           
            datap[item] = body;
            json.data = datap;
            if(item == singers.length -1 ){
        
                reslove();
            }
           }
         })
      })
     })
 }
,
 data : 'zzzzz',
 dataParser : ()=>{
    return new Promise((reslove, reject)=>{
        let singerDataArr  = json.data; 
        let musicDatas = [];
        //获取每一个的歌手的歌曲url
        singerDataArr.forEach(function(index, item){
        let singerData = JSON.parse(index);
        ///针对每一个歌手的热门歌曲
        singerData.hotSongs.forEach(function(index, item){
        let songsData = {
            'name':index.name,
            'id':index.id,
            'url':`http://music.163.com/song/media/outer/url?id=${index.id}.mp3`,
            'number':item+1,
            'musician': index.ar[0].name,
            'alImg':index.al.picUrl,
            'dt':index.dt,
            }
            musicDatas.push(songsData);
            })
            })
        reslove(musicDatas);

        })
 },
 storage : (data)=>{
     return new Promise((reslove, reject)=>{
            fs.writeFile('./Data/musicData.json', JSON.stringify(data) ,()=>{
            reslove();
        })
     })
 }
}
module.exports = function(){

   return json.updata().then(json.request).then(json.dataParser).then(json.storage)

};

